package com.colin.ui.component;

import com.colin.database.MysqlDataSource;
import org.jdesktop.swingx.JXList;
import org.jdesktop.swingx.JXTextField;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SearchComboBox extends JPanel {

    private DefaultListModel<String> listModel;
    private JXTextField searchTextField;
    private JXList searchList;

    public SearchComboBox() {
        setLayout(new BorderLayout());

        listModel = new DefaultListModel<>();
        searchTextField = new JXTextField();
        searchList = new JXList(listModel);

        // 添加列表滚动面板
        JScrollPane scrollPane = new JScrollPane(searchList);
        scrollPane.setPreferredSize(new Dimension(200, 150));

        // 监听搜索框输入事件
        searchTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                String searchValue = searchTextField.getText().toLowerCase();
                updateList(searchValue);
            }
        });

        add(searchTextField, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
    }

    private void updateList(String searchValue) {
        listModel.clear();
        List<String> filteredItems = filterItems(searchValue);
        for (String item : filteredItems) {
            listModel.addElement(item);
        }
    }

    private List<String> filterItems(String searchValue) {
        List<String> items = MysqlDataSource.executeSQL("show tables", String.class, (resultSet) -> {
            try {
                return resultSet.getString("Tables_in_icms");
            } catch (SQLException ex) {
                return "UNKONWN";
            }
        });

        List<String> filteredItems = new ArrayList<>();
        for (String item : items) {
            if (item.toLowerCase().contains(searchValue)) {
                filteredItems.add(item);
            }
        }

        return filteredItems;
    }

    public static void main(String[] args) {
        System.out.println(new ArrayList<Long>().stream()
                .allMatch(e -> Long.valueOf(0L).equals(e)));
    }
}
